<?php

namespace CckSso\Services;

use Overtrue\Socialite\SocialiteManager;

/**
 * 第三方登录
 */
class PartnerService
{
    /**
     * @var array 存放第三方配置
     */
    private $config;
    
    /**
     * @var object 第三方服务对象
     */
    private $service;
    
    /**
     * 初始化
     */
    public function __construct() 
    {
        $this->config = config('sso.partners');
        
        $this->service = new SocialiteManager($this->config);
    }
    
    /**
     * 跳转到第三方授权页面
     * 
     * @param string $partner 第三方名称 (facebook, github, google, linkedin, outlook, weibo, qq, wechat, and douban)
     * @param array $scopes 第三方赋予的权限
     * @redirect 第三方
     */
    public function redirect($partner, $scopes = [])
    {
        $driver = $this->service->driver($partner);
        if ($scopes) {
            $driver = $driver->scopes($scopes);
        }
        return $driver->redirect();
    }
    
    /**
     * 第三方回调
     * 
     * @param string $partner 第三方名称 (facebook, github, google, linkedin, outlook, weibo, qq, wechat, and douban)
     * @return array
     */
    public function callback($partner)
    {
        try {
            $user = $this->service->driver($partner)->user();
            return $user->jsonSerialize();
        } catch (Exception $e) {
            return [];
        }
    }
    
}
